﻿using rateITcd.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace rateITcd.Controllers
{
    public class AdminController : Controller
    {
        ApplicationDbContext context = new ApplicationDbContext();

        public ActionResult Index()
        {
            var roles = context.Roles.ToList();
            return View(roles);
        }

        public ActionResult Delete(string RoleName)
        {
            var thisRole = context.Roles.Where(r => r.Name.Equals(RoleName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            context.Roles.Remove(thisRole);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        // GET: Admin
        // GET: /Roles/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Roles/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
                {
                    Name = collection["RoleName"]
                });
                context.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Admin
        // GET: /Roles/CreateUser
        public ActionResult CreateUser()
        {
            return View();
        }

        //
        // POST: /Roles/Create
        [HttpPost]
        public ActionResult CreateUser(RegisterViewModel model)
        {
            try
            {
                UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(
                 new UserStore<ApplicationUser>(new ApplicationDbContext()));
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = _userManager.Create(user, model.Password);
                context.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Roles/Edit/5
        public ActionResult Edit(string roleName)
        {
            var thisRole = context.Roles.Where(r => r.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            return View(thisRole);
        }

        //
        // POST: /Roles/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Microsoft.AspNet.Identity.EntityFramework.IdentityRole role)
        {
            try
            {
                context.Entry(role).State = System.Data.Entity.EntityState.Modified;
                context.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult ManageUserRoles()
        {
            // prepopulat roles for the view dropdown
            var roleList = context.Roles.OrderBy(r => r.Name).ToList().Select(
                rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            var userList = context.Users.OrderBy(r => r.Email).ToList().Select(
                rr => new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList();

            ViewBag.Users = userList;
            ViewBag.Roles = roleList;
            return View();
        }

        public ActionResult ManageUsers()
        {

            var userList = context.Users.OrderBy(r => r.Email).ToList().Select(
                rr => new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList();
            ViewBag.Users = userList;

            return View();
        }

        public ActionResult ManageUser(string Email)
        {
                if (Email == null)
                {
                    return View("ManageUsers");
                }
                UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(
                     new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = context.Users.Where(u => u.Email.Equals(Email, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                ViewBag.UserId = user.Id;
                ViewBag.UserEmail = user.Email;
                ViewBag.UserUserName = user.UserName;
                return View();

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleAddToUser(string UserName, string RoleName)
        {
            ApplicationUser user = context.Users.Where(u => u.Email.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            //var account = new AccountController();
            //account.UserManager.AddToRole(user.Id, RoleName);
            UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(
                 new UserStore<ApplicationUser>(new ApplicationDbContext()));
            _userManager.AddToRole(user.Id, RoleName);
            ViewBag.ResultMessage = "Role created successfully !";

            // prepopulat roles for the view dropdown
            var roleList = context.Roles.OrderBy(r => r.Name).ToList().Select(
                rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            var userList = context.Users.OrderBy(r => r.Email).ToList().Select(
                rr => new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList();
            ViewBag.Users = userList;
            ViewBag.Roles = roleList;
            return View("ManageUserRoles");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult GetRoles(string UserName)
        {
            if (!string.IsNullOrWhiteSpace(UserName))
            {
                ApplicationUser user = context.Users.Where(u => u.Email.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                //var account = new AccountController();
                UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(
     new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ViewBag.RolesForThisUser = _userManager.GetRoles(user.Id);

                // prepopulate roles for the view dropdown
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                var userList = context.Users.OrderBy(r => r.Email).ToList().Select(rr => new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList();

                ViewBag.Users = userList;
                ViewBag.Roles = list;
            }

            return View("ManageUserRoles");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {
            //var account = new AccountController();
            UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(
                new UserStore<ApplicationUser>(new ApplicationDbContext()));
            ApplicationUser user = context.Users.Where(u => u.Email.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            if (_userManager.IsInRole(user.Id, RoleName))
            {
                _userManager.RemoveFromRole(user.Id, RoleName);
                ViewBag.ResultMessage = "Role removed from this user successfully !";
            }
            else
            {
                ViewBag.ResultMessage = "This user doesn't belong to selected role.";
            }
            // prepopulat roles for the view dropdown
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            var userList = context.Users.OrderBy(r => r.Email).ToList().Select(rr => new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList();

            ViewBag.Users = userList;
            ViewBag.Roles = list;

            return View("ManageUserRoles");
        }


    }
}